<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文将详细剖析Canal在初次启动时如何定位同步位点，行为思路先源码，再辅以流程图进行说明，并在总结部分使用思维导图进行总结，试图引发各位的讨论。 1、Canal定位启动位点在一个 Canal Instance 实例启动时，在向 MySQL 发送 dump 命令之前，首先先得计算该从 binlog 的什么位置开始同步，初次启动时如何寻找位点等。其代码如下图所示：从这里可以看成，将调用 findSt">
<meta property="og:type" content="article">
<meta property="og:title" content="Canal 初次启动时如何定位同步位点(文末附流程图)">
<meta property="og:url" content="https://www.codingw.net/posts/dcbc2c14.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文将详细剖析Canal在初次启动时如何定位同步位点，行为思路先源码，再辅以流程图进行说明，并在总结部分使用思维导图进行总结，试图引发各位的讨论。 1、Canal定位启动位点在一个 Canal Instance 实例启动时，在向 MySQL 发送 dump 命令之前，首先先得计算该从 binlog 的什么位置开始同步，初次启动时如何寻找位点等。其代码如下图所示：从这里可以看成，将调用 findSt">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150553488.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150633861.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150704437.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150726743.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150813198.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150831508.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150856825.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150911285.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719150952220.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020071915102882.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020071915111442.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020071915113412.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020071915115830.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719152049556.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719152108279.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719151412889.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020071915143632.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719151456693.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719152416688.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719152451570.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200719152508266.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2020-11-18T14:00:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:12:53.278Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200719150553488.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/dcbc2c14.html"/>





  <title>Canal 初次启动时如何定位同步位点(文末附流程图) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/dcbc2c14.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Canal 初次启动时如何定位同步位点(文末附流程图)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-18T22:00:01+08:00">
                2020-11-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/canal/" itemprop="url" rel="index">
                    <span itemprop="name">canal</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/dcbc2c14.html" class="leancloud_visitors" data-flag-title="Canal 初次启动时如何定位同步位点(文末附流程图)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本文将详细剖析Canal在初次启动时如何定位同步位点，行为思路先源码，再辅以流程图进行说明，并在总结部分使用思维导图进行总结，试图引发各位的讨论。</p>
<h2 id="1、Canal定位启动位点"><a href="#1、Canal定位启动位点" class="headerlink" title="1、Canal定位启动位点"></a>1、Canal定位启动位点</h2><p>在一个 Canal Instance 实例启动时，在向 MySQL 发送 dump 命令之前，首先先得计算该从 binlog 的什么位置开始同步，初次启动时如何寻找位点等。其代码如下图所示：<br><img src="https://img-blog.csdnimg.cn/20200719150553488.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="AbstractEventParser#start"><br>从这里可以看成，将调用 findStartPosition 方法查找启动时需要从那个位置开始同步 binglog ,该方法是一个抽象方法，具体实现在其子类中，我们将重点关注一下其子类 MysqlEventParser。<br><img src="https://img-blog.csdnimg.cn/20200719150633861.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findStartPostion"><br>在MySQL中定位binlog日志可以分为gtid、binlog文件名+position两种方式，故Canal查找position的方式也分两种情况进行展开，由于篇幅问题，本节将暂不考虑gtid。</p>
<p>这里主要是调用 findStartPositionInternal 方法进行查找位点，这里还有一个标记 needTransactionPosition，表示查出来的位点是不是一个事务的开始或结束。</p>
<p>接下来重点探讨 Canal在启动时如何定位解析位点的。</p>
<span id="more"></span>

<h4 id="1-1-查找位点"><a href="#1-1-查找位点" class="headerlink" title="1.1 查找位点"></a>1.1 查找位点</h4><p><img src="https://img-blog.csdnimg.cn/20200719150704437.png#pic_center" alt="MysqlEventParser#findStartPositionInternal"><br>Step1：使用位点存储管理器中查看已解析过的位点数据，Canal 提供了多种日志管理实现，这部分稍后会详细展开。<br><img src="https://img-blog.csdnimg.cn/20200719150726743.png#pic_center" alt="MysqlEventParser#findStartPositionInternal">Step2：这里分如下两种情况</p>
<ul>
<li>如果日志位点管理器(LogPositionManager)中并未存储相关的位点信息，例如初次启动时的处理逻辑。</li>
<li>如果日志位点管理器中已存储相关的位点信息的处理逻辑。</li>
</ul>
<p>由于初次启动时日志位点管理器并没有存储其位点信息，故我们先看位点管理器并未存储位点的情况。<br><img src="https://img-blog.csdnimg.cn/20200719150813198.png#pic_center" alt="MysqlEventParser#findStartPositionInternal"><br>Step3：如果当前连接的是主节点，则尝试使用 masterPosition，如果当前连接的是从节点（发生了切换），即使用 standbyPosition，那这两个位点信息是从哪来的的呢？原来在 Canal Instance 实例启动之前，可以手动通过 positions 属性手动设置开始解析位点。<br><img src="https://img-blog.csdnimg.cn/20200719150831508.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findStartPositionInternal">Step4：如果在启动时未手动设置初始解析位点，则从当前 binlog 日志最后的位点开始同步，其实现原理是向 MySQL 服务器发送 show master status\G 命令，其命令输出结果如下图所示：<br><img src="https://img-blog.csdnimg.cn/20200719150856825.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center"><br>接下来再关注一下如果从日志位点管理器中查找到位点的处理逻辑，在进入该流程的探究之前，先看一下表示位点的实体类，一睹其结构。<br><img src="https://img-blog.csdnimg.cn/20200719150911285.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>会在 LogIdentity 中记录该日志位点是由哪个 slaveId 以及所连接的 MySQL 服务器信息。<br><img src="https://img-blog.csdnimg.cn/20200719150952220.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findStartPositionInternal"><br>Step5：如果从日志位点管理器中查询到位点，则需要判断当前连接的服务器地址与日志位点中记录的是否一致，如果不一致则说明发生了故障切换，为了确保数据不丢失，提供了回退时间的机制，其具体实现关键点如下：</p>
<ul>
<li>如果解析 dump 出现的次数超过其阔值，可能是基于VIP模式发生了漂移，此时可以根据 serverId 来判断是否发生了切换，如何切换了，则按时间回退来重新寻找位点。</li>
<li>如果查找到的位点连接的信息与当前连接的信息不符合，说明发生了切换，则需要回退指定的时间，即根据时间区重新定位位点，至于回退多久的时间，可以通过参数 fallbackIntervalInSeconds 进行设置，默认为 60s。</li>
</ul>
<p>Canal Instance 启动时如何定位同步位点的流程就介绍到这里了，接下来我们再来看一下 Canal 如何基于时间戳来定位 binlog 位点。</p>
<p>为了流程的完整性，在学习如何根据时间戳查找binlog位点之前，我们先来看一下从位点管理器中查询到对应的位点信息后的处理流程。<br><img src="https://img-blog.csdnimg.cn/2020071915102882.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findStartPositionInternal">如果从位点管理器中查询到位点信息，首先判断当前连接的MySQL服务器(主或从)与位点信息是否一致，如果不一致，说明发生了主从切换，为了保证数据的完整性，需要对位点进行前移，默认为回退到60s之前的位点，</p>
<h4 id="1-2-基于时间戳从查找-binlog-位点"><a href="#1-2-基于时间戳从查找-binlog-位点" class="headerlink" title="1.2 基于时间戳从查找 binlog 位点"></a>1.2 基于时间戳从查找 binlog 位点</h4><p>基于时间戳查找 binlog 位点的实现方法为 MysqlEventParser 的　findByStartTimeStamp，接下来我们来看一下其实现原理。<br><img src="https://img-blog.csdnimg.cn/2020071915111442.png#pic_center" alt="MysqlEventParser#findByStartTimeStamp"><br>Step1：首先先查询最大的位点与最小位点，最小位点可发送SQL：show binlog events limit 1。<br><img src="https://img-blog.csdnimg.cn/2020071915113412.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findByStartTimeStamp"><br>Step2：然后从最后一个文件开始，尝试根据开始时间戳进行日志查找，等下会详细介绍如果从一个binlog日志定位 endposition。<br><img src="https://img-blog.csdnimg.cn/2020071915115830.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findByStartTimeStamp"><br>Step3：如果找到一个合适的endposition，则结束寻找。如果没有找到一个合适的endposition，则尝试向前一个文件进行解析，首先解析出要查找的最小文件的名称，例如(mysql-bin.000036)，从文件名称序号，然后减1，再判断该文件名是否小于这次可查找的最小文件名，如果不大于，则向前继续选择，否则结束查找，返回null。</p>
<p>接下来我们看一下如果在一个binlog文件中根据时间戳查找合适的位点。<br><img src="https://img-blog.csdnimg.cn/20200719152049556.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="MysqlEventParser#findAsPerTimestampInSpecificLogFile"><br>通过向 MySQL Master 发送 dump 命令，建立连接，一条一条从 binlog 日志中解析事件，一条日志日志进行匹配，每从master获取一个logevent，调用 SinkFunction 的 seek 方法。<br><img src="https://img-blog.csdnimg.cn/20200719152108279.png#pic_center" alt="在这里插入图片描述"><br>Step1：如果 justForPositionTimestamp 参数为 true，表示在查询位点时只考虑时间戳，并不考虑事务，在按开始时间戳寻找的方法中该参数为 false，即不会进入该方法。<br><img src="https://img-blog.csdnimg.cn/20200719151412889.png#pic_center" alt="SinkFunction#sink"><br>Step2：获取当前日志的基本信息，例如所在的binlog日志文件、日志偏移量、日志写入时间戳、master serverId。<br><img src="https://img-blog.csdnimg.cn/2020071915143632.png#pic_center" alt="SinkFunction#sink"><br>Step3：如果记录日志的时间戳大于等于待查找的时间戳，返回 false，停止在文件中的停止，是否继续查找其他文件取决在在当前文件中是否已查到符合条件的日志(LogEvent)，即是否查找到小于或等于要查找的时间戳。</p>
<blockquote>
<p>温馨提示：按照时间戳去查找，其设计理念就是查找小于待查找时间戳中的最大时间戳的LogEvent。</p>
</blockquote>
<p><img src="https://img-blog.csdnimg.cn/20200719151456693.png#pic_center" alt="SinkFunction#sink"><br>Step4：如果当前的解析的日志偏移量小于此次待查找的最大偏移量，同样结束本文件的查找（针对查找的第一个文件）。因为在查询的时候，首先会查询当前最大偏移量，即查找时的快照，新的内容不在本次查找范围内。<br><img src="https://img-blog.csdnimg.cn/20200719152416688.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>Step5：重点查找事件类型为TRANSACTIONEND与TRANSACTIONBEGIN ，即事务结束与事务开始的事件，并将其存储在 logPostion 中，表示该文件中满足查找条件的事件，但并不是只要找到一条就退出，而是继续向后找，直到找到最合适的事件。</p>
<p>由于源码剖析不够直观，为了更好的理解按照时间戳查找日志位点，再给出其流程图，如下：<br><img src="https://img-blog.csdnimg.cn/20200719152451570.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
<h2 id="2、总结"><a href="#2、总结" class="headerlink" title="2、总结"></a>2、总结</h2><p>阅读源码不那么直观，故先来一张流程图对其进行一个总结，辅助大家了解定位位点的核心步骤。<br><img src="https://img-blog.csdnimg.cn/20200719152508266.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/d0c99696.html" rel="next" title="Canal 如何实现数据库库事务的一致性">
                <i class="fa fa-chevron-left"></i> Canal 如何实现数据库库事务的一致性
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/f051946a.html" rel="prev" title="Canal binlog 日志管理器与GTID简介">
                Canal binlog 日志管理器与GTID简介 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81Canal%E5%AE%9A%E4%BD%8D%E5%90%AF%E5%8A%A8%E4%BD%8D%E7%82%B9"><span class="nav-number">1.</span> <span class="nav-text">1、Canal定位启动位点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-%E6%9F%A5%E6%89%BE%E4%BD%8D%E7%82%B9"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.1 查找位点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E5%9F%BA%E4%BA%8E%E6%97%B6%E9%97%B4%E6%88%B3%E4%BB%8E%E6%9F%A5%E6%89%BE-binlog-%E4%BD%8D%E7%82%B9"><span class="nav-number">1.0.2.</span> <span class="nav-text">1.2 基于时间戳从查找 binlog 位点</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%80%BB%E7%BB%93"><span class="nav-number">2.</span> <span class="nav-text">2、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
